package com.yydm.serviceedu.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.yydm.servicebase.exceptionhandler.LException;
import com.yydm.serviceedu.service.VodService;
import com.yydm.serviceedu.utils.InitVodClient;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @Classname VodServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/6/28 21:01
 * @Created by liu25
 */
@Service
public class VodServiceImpl implements VodService {

    //    上传视频到云端
    @Override
    public String uploadVideo(MultipartFile file) {
        try {
            //    accessKeyId id
            //    accessKeySecret 秘钥
            //    fileName 上传文件原始名称
            String fileName = file.getOriginalFilename();
            //    title 上传之后显示名称 11.mp4从.截取
            String title = fileName.substring(0, fileName.lastIndexOf("."));

            //    inputStream 上传文件输入流
            InputStream inputStream = file.getInputStream();

            UploadStreamRequest request = new UploadStreamRequest("LTAI5tMYnwt1GGNoDMdJbCTA",
                    "I1cbg8ahhGfe7spQ292p1YepoGFP5X",
                    title, fileName, inputStream);
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }
            return videoId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //    删除云端上的视频
    @Override
    public void removeVideo(String videoId) {
        try {
            DefaultAcsClient client = InitVodClient.initVodClient("LTAI5tMYnwt1GGNoDMdJbCTA",
                    "I1cbg8ahhGfe7spQ292p1YepoGFP5X");
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoId);
            DeleteVideoResponse response = client.getAcsResponse(request);
            System.out.println("RequestId=" + response.getRequestId());
        } catch (Exception e) {
            throw new LException(500, "视频删除失败");
        }
    }
}
